/*
 * -------------------------------------------------------------------------
 * 渲染进程对话框管理
 * -------------------------------------------------------------------------
 */

/*app对象实例*/
let app;
const _          = require('lodash');
const fs         = require('fs');
const electron   = require('electron');
const ipcMain    = electron.ipcMain;
const dialog     = electron.dialog;
const shell      = electron.shell;
const IPC_DIALOG = require('../ipc/dict').IPC_DIALOG;

/*筛选过滤规则*/
const filters = [
    {
        name      : 'All',
        extensions: ['*']
    },
    {
        name      : 'Images',
        extensions: ['jpg', 'jpeg', 'png', 'gif', 'bmp']
    },
    {
        name      : 'Movies',
        extensions: ['mkv', 'avi', 'mp4', 'flv']
    },
    {
        name      : 'Json File',
        extensions: ['json']
    }
];

/**
 * 初始化
 * @param appInstance
 */
function initialize (appInstance) {
    /*复写app实例*/
    app = appInstance;
    
    /*获取主窗口*/
    let win = app.$windowMain;
    
    /**
     * 保存文件
     */
    ipcMain.on(IPC_DIALOG.SAVE_FILE, (e, { title, filter, properties, data }) => {
        /*查询过滤规则*/
        let filterKey = _.findIndex(filters, { name: filter || '' });
        
        /*过滤列表*/
        let filterList = [];
        filterList.push(filters[_.findIndex(filters, { name: 'All' })]);
        if (filterKey >= 0 && filter !== 'All') filterList.push(filters[filterKey]);
        
        /*文件名*/
        let file;
        
        /*文件内容*/
        let dataBuffer;
        
        /*保存图片*/
        if (filter === 'Images') {
            /*匹配图片格式*/
            let res = /^data\:(.*?)\/(.*?);base64,/i.exec(data);
            
            /*文件名*/
            file = res ? `${(+new Date())}.${res[2]}` : '';
            
            /*图片base64内容*/
            dataBuffer = new Buffer(data.replace(/^data:(.*?)\/(.*?);base64,/, ''), 'base64');
        }
        
        /*其他文件*/
        else {
            /*if (filter === 'Json File')*/
            
            /*文件名*/
            file = (+new Date()).toString();
            
            /*图片base64内容*/
            dataBuffer = data;
        }
        
        /*打开窗口*/
        let handler = dialog.showSaveDialog(win, {
            title      : title || '保存',
            buttonLabel: '保存',
            defaultPath: file,
            properties : properties || ['showHiddenFiles'], /*showHiddenFiles 显示隐藏文件*/
            filters    : filterList
        });
        
        /*成功*/
        handler.then(res => {
            if (!res.filePath) return;
            
            res.errCode = 0;
            
            /*写文件*/
            fs.writeFile(res.filePath, dataBuffer, err => {
                if (err) {
                    res.errCode = 1;
                    res.errMsg  = JSON.stringify(err);
                    win.webContents.send(IPC_DIALOG.SAVE_FILE_RESULT, res);
                    return;
                }
                
                /*弹出保存文件夹*/
                shell.showItemInFolder(res.filePath);
                
                /*发送选择结果*/
                win.webContents.send(IPC_DIALOG.SAVE_FILE_RESULT, res);
            });
        });
        
        /*错误*/
        handler.catch(err => {
            win.webContents.send(IPC_DIALOG.SAVE_FILE_RESULT, {
                errCode: 1,
                errMsg : JSON.stringify(err)
            });
        });
    });
    
    /**
     * 选择文件
     */
    ipcMain.on(IPC_DIALOG.SELECT_FILES, (e, { title, filter, properties, getBase64 }) => {
        /*查询过滤规则*/
        let filterKey = _.findIndex(filters, {
            name: filter || 'All'
        });
        
        /*未找到规则使用默认*/
        filterKey = filterKey < 0 ? 0 : filterKey;
        
        /*打开窗口*/
        let handler = dialog.showOpenDialog(win, {
            title: title || '选择',
            /*openFile,openDirectory,multiSelections,showHiddenFiles*/
            properties: properties || ['openFile', 'showHiddenFiles'],
            filters   : [filters[filterKey]]
        });
        
        /*成功*/
        handler.then(res => {
            res.errCode = 0;
            
            /*文件转base64*/
            if (getBase64 === true && res.filePaths) {
                /*不支持多文件*/
                if (res.filePaths.length > 1) {
                    res.errCode = 1;
                    res.errMsg  = '转换base64选项仅支持选择1个文件';
                    win.webContents.send(IPC_DIALOG.SELECT_FILES_RESULT, res);
                    return;
                }
                
                /*单文件转base64*/
                if (res.filePaths.length === 1) {
                    /*读取文件*/
                    fs.readFile(res.filePaths[0], (err, data) => {
                        if (err) {
                            res.errCode = 1;
                            res.errMsg  = JSON.stringify(err);
                            win.webContents.send(IPC_DIALOG.SELECT_FILES_RESULT, res);
                            return;
                        }
                        
                        /*将buffer对象转为base64*/
                        res.base64 = Buffer.from(data).toString('base64');
                        win.webContents.send(IPC_DIALOG.SELECT_FILES_RESULT, res);
                    });
                    return;
                }
                
                /*未选择文件不处理*/
            }
            
            /*发送选择结果*/
            win.webContents.send(IPC_DIALOG.SELECT_FILES_RESULT, res);
        });
        
        /*失败*/
        handler.catch(err => {
            win.webContents.send(IPC_DIALOG.SELECT_FILES_RESULT, {
                errCode: 1,
                errMsg : JSON.stringify(err)
            });
        });
    });
}

/**
 * 导出
 * @type {{initialize: initialize}}
 */
module.exports = {
    initialize
};
